package cn.chaozhoubang.vmall.backend.controller.impl;

import cn.chaozhoubang.vmall.backend.annotation.AuthRequire;
import cn.chaozhoubang.vmall.backend.controller.GoodsController;
import cn.chaozhoubang.vmall.backend.mapper.GoodsMapper;
import cn.chaozhoubang.vmall.backend.model.SpGoods;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/private/v1")
public class GoodsControllerImpl implements GoodsController {
    @Autowired
    private GoodsMapper goodsMapper;

    private JSONObject buildData() {
        final JSONObject data = new JSONObject();
        return data;
    }

    private JSONObject buildMeta(int status, String msg) {
        final JSONObject meta = new JSONObject();
        meta.set("status", status);
        meta.set("msg", msg);
        return meta;
    }

    private JSONArray buildArray( List<SpGoods> list) {
        final JSONArray array = new JSONArray();
        for(SpGoods spGoods:list){
            final JSONObject object = new JSONObject();
            object.set("goods_id",spGoods.getGoodsId())
                    .set("goods_name",spGoods.getGoodsName())
                    .set("goods_price",spGoods.getGoodsPrice())
                    .set("goods_number",spGoods.getGoodsNumber())
                    .set("goods_weight",spGoods.getGoodsWeight())
                    .set("goods_state",spGoods.getGoodsState())
                    .set("add_time",spGoods.getAddTime())
                    .set("upd_time",spGoods.getUpdTime())
                    .set("hot_mumber",spGoods.getHotMumber())
                    .set("is_promote",spGoods.getIsPromote());
            array.add(object);
        }
        return array;
    }

    private JSONObject buildData(IPage<SpGoods> page) {
        final JSONObject data = new JSONObject();
        List<SpGoods> list = page.getRecords();
        data.set("total",page.getTotal())
                .set("pagenum",page.getCurrent()).set("goods",buildArray(list));
        return data;
    }

    private JSONObject buildResult(JSONObject meta, JSONObject data) {
        final JSONObject res = new JSONObject();
        res.set("meta", meta);
        res.set("data", data);
        return res;
    }

    private JSONObject buildInsertData(SpGoods sp){
        final JSONObject object = new JSONObject();
        Date date3 = DateUtil.date(System.currentTimeMillis());
             object.set("goods_id", sp.getGoodsId())
                .set("goods_name", sp.getGoodsName())
                .set("goods_price", sp.getGoodsPrice())
                .set("cat_id", sp.getCatId())
                .set("goods_number",sp.getGoodsNumber())
                .set("goods_weight",sp.getGoodsWeight())
                .set("goods_introduce",sp.getGoodsIntroduce())
                .set("goods_big_logo",null)
                .set("goods_small_logo",null)
                .set("goods_state",1)
                .set("add_time",date3).set("upd_time",date3)
                     .set("hot_mumber",0).set("is_promote",false)
                     .set("pics",null).set("attrs",null);
        return object;
    }

    @Override
    @AuthRequire
    @GetMapping(value = "/goods",produces = "application/json;charset=UTF-8")
    public String getGoods(@RequestParam(defaultValue = "")String query, int pagenum,int pagesize) {
        QueryWrapper<SpGoods> wrapper = new QueryWrapper<>();
        if(!"".equals(query))
            wrapper.like("goods_name", "%" + query + "%");
        Page<SpGoods> page = new Page<>(pagenum, pagesize);
        IPage<SpGoods> paging = goodsMapper.selectPage(page,wrapper);
        final JSONObject data = buildData(paging);
        final JSONObject meta = buildMeta(200, "获取成功");
        return buildResult(meta, data).toString();
    }

    @Override
    @PostMapping(value = "/goods",produces = "application/json;charset=UTF-8")
    public String addGoods(@RequestBody String jsonStr) {
        final JSONObject json = JSONUtil.parseObj(jsonStr);
        if(!json.containsKey("goods_name") || !json.containsKey("goods_cat") || !json.containsKey("goods_price") || !json.containsKey("goods_number") || !json.containsKey("goods_weight")) {
            return buildResult(buildMeta(400, "参数异常!"), new JSONObject()).toString();
        }
        String[] cats = ((String) json.get("goods_cat")).split(",");
        SpGoods spGoods = new SpGoods();
        spGoods.setCatOneId(Integer.parseInt(cats[0]));
        spGoods.setCatTwoId(Integer.parseInt(cats[1]));
        spGoods.setCatThreeId(Integer.parseInt(cats[2]));
        spGoods.setCatId(Integer.parseInt(cats[2]));
        spGoods.setGoodsIntroduce((String) json.get("goods_introduce"));
        spGoods.setGoodsName((String) json.get("goods_name"));
        spGoods.setGoodsNumber(Long.parseLong((String) json.get("goods_number")));
        spGoods.setIsPromote(Long.parseLong((String) json.get("goods_price")));
        spGoods.setGoodsWeight(Long.parseLong((String) json.get("goods_weight")));

        final JSONObject param = JSONUtil.parseObj(spGoods);
        System.out.println(spGoods);

        String goods_name = spGoods.getGoodsName();
        double goods_price = spGoods.getGoodsPrice();
        long goods_number = spGoods.getGoodsNumber();
        long goods_weight = spGoods.getGoodsWeight();
        String goods_introduce = (String) param.get("goods_introduce");

        SpGoods spGoods1 = new SpGoods();
        spGoods1.setGoodsName(goods_name);
        spGoods1.setGoodsPrice(goods_price);
        spGoods1.setGoodsNumber(goods_number);
        spGoods1.setGoodsWeight(goods_weight);
        spGoods1.setGoodsIntroduce(goods_introduce);

        int res = goodsMapper.insert(spGoods1);
        if(res != 0){
            final QueryWrapper<SpGoods> wrapper = new QueryWrapper<>();
            wrapper.eq("goods_name", goods_name);
            final SpGoods sp = goodsMapper.selectOne(wrapper);
            final JSONObject data = buildInsertData(sp);
            final JSONObject meta = buildMeta(201, "添加成功");
            return buildResult(meta,data).toString();
        }else {
            return buildResult(buildMeta(500, "添加失败!"), new JSONObject()).toString();
        }
    }

    @Override
    @DeleteMapping(value = "/goods/{id}", produces = "application/json;charset=UTF-8")
    public String deleteGoods(@PathVariable("id")int id) {
        QueryWrapper<SpGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id",id);
        SpGoods spGoods = goodsMapper.selectOne(wrapper);
        if(spGoods == null){
            final JSONObject meta = buildMeta(400, "商品不存在");
            return  meta.toString();
        }
        int res = goodsMapper.deleteById(id);
        if(res != 0){
            final JSONObject meta = buildMeta(200, "删除成功");
            final JSONObject data = buildData();
            return buildResult(meta,data).toString();
        }else {
            final JSONObject meta = buildMeta(400, "删除失败");
            final JSONObject data = buildData();
            return buildResult(meta,data).toString();
        }
    }
}
